<template>
	<view class="relative full-screen">
		<view style="z-index:0;position:absolute;left:0;right:0;top:0;height:396px;background-image:radial-gradient(circle at left top, #D8230A26 50%, transparent 50%);background-size:396px 396px;background-repeat:no-repeat;filter:blur(50px);"></view>
		<z-paging
			ref="paging"
			:auto="false"
			:default-page-size="queryParams.pageSize"
			v-model="list"
			@query="queryList"
			@scroll="handleScroll"
		>
			<template #top>
				<uni-nav-bar ref="navBar" statusBar :border="false" backgroundColor="transparent"
					left-width="0" :rightWidth="menuButtonInfo.width">
					<view class="flex item-center w-full">
						<!-- <view class="flex item-center mr-20">
							<image src="@/static/image/home-logo.png" class="size-32 mr-4">
							</image>
							<view class="flex flex-col">
								<text class="uni-primary fs-14 text-bold">火动通告</text>
								<text class="fs-8">一秒搞定周末活动</text>
							</view>
						</view> -->
						<view class="flex-1 flex item-center px-8 py-4 h-32 bg-white c9 fs-12 font-normal whitespace-nowrap text-cut" style="border-radius:44rpx;" @click="gotoSearch">
							<image src="@/static/svg/icon-search.svg" class="size-20 mr-4"></image>
							<text>搜活动</text>
						</view>
					</view>
				</uni-nav-bar>
				<view class="wx-pub flex item-center justify-between" v-if="userStore.isIndexWxPubShow">
					<view class="wx-pub-text">关注公众号，接收活动和订单通知</view>
					<view class=" flex item-center">
						<view class="wx-button" @click="openWxPop">关注</view>
						<image src="../../static/svg/icon-close-tip.svg" mode="widthFix" class="icon-clean" @click="closePub"></image>
					</view>
					
				</view>
				<view class="flex tabs mt-10 ml-20 flex-shrink pb-12">
					<view v-for="item in tabs" :key="item.value" class="inline-flex flex-col center tab-item c3 text-center fs-16 font-normal mr-32"
						@click="()=>onClickTab(item.value)">
						<text :style="currentTab===item.value?'font-weight:600;background:linear-gradient(76deg, #FF2043 11.75%, #FF5632 97.32%);background-clip:text;-webkit-background-clip:text;-webkit-text-fill-color:transparent;':''">{{item.text}}</text>
						<view v-if="currentTab===item.value" class="flex justify-center">
							<image class="w-15 h-3" src="@/static/svg/tab-indicate.svg"></image>
						</view>
					</view>
					<view v-if="city" class="flex-1 flex justify-end item-center fs-12 c3 mr-12" @click="toSelectCity">
						<image class="size-20 mr-4" src="@/static/svg/icon-location.svg"></image>
					{{city}}
					</view>
				</view>
				<view v-if="userStore && userStore.userInfo && userStore.userInfo.agentLevel !== 0 && currentTab === 4" class="flex tabs mt-10 ml-20 flex-shrink pb-12">
					<view v-for="item in tabs2" :key="item.value" class="inline-flex flex-col center tab-item c3 text-center fs-16 font-normal mr-32"
						@click="()=>onClickTab2(item.value)">
						<text :style="currentTab2===item.value?'font-weight:600;background:linear-gradient(76deg, #FF2043 11.75%, #FF5632 97.32%);background-clip:text;-webkit-background-clip:text;-webkit-text-fill-color:transparent;':''">{{item.text}}</text>
					</view>
				</view>
			</template>
			<view class="mx-16 flex-col">
				<view v-if="currentTab===1" class="fs-12 c3-6 mt-12 mb-8" @click="toMySubscribe">我的订阅 ></view>
				<ActivityItem
					v-for="(item,index) in list"
					:key="index"
					:data="item"
					:preCity="list[index - 1] ? list[index - 1].cityName : ''"
					:currentCity="city"
					:index="index"
					class="mb-16"
					@refresh="refreshState"
					@share="toShare(item)"
				/>
			</view>
			<template #empty>
				<EmptyActivity />
			</template>
			<template #loadingMoreNoMore>
				<view :style="userStore.isLogin && userStore.isMerchant ? `height:calc(120px + ${safeAreaBottom}px);` : `height:calc(90px + ${safeAreaBottom}px);`">
					<view class="text-center text-color-hint fs-14">到底了～</view>
				</view>
			</template>
		</z-paging>
		<ScrollToTop v-if="showBackToTop" :bottom="safeAreaBottom" @backToTop="backToTop" />
		<popWxpub ref="wxPubRef"></popWxpub>
		<share-activity :id="shareId" :show="showSharePopup" @onClose="showSharePopup=false" />
	</view>
</template>

<script setup name="Home">
	import {
		onMounted,
		ref,
		unref,
		computed,
		getCurrentInstance
		
	} from 'vue'
	import {onShow} from '@dcloudio/uni-app'
	import {
		useUserStore
	} from '@/stores/modules/user.js'
	import EmptyActivity from './components/EmptyActivity.vue'
	import ActivityItem from './components/ActivityItem.vue'
	import ScrollToTop from './components/ScrollToTop.vue'
	import { getPositionApi } from '@/api/index.js'
	import { getSubscribeState } from '@/api/auth.js'
	import { pageIndexActiveApi } from '@/api/activity.js'
	import popWxpub from '@/pagesE/components/popup-wxPub/popup-wxPub.vue'
	const userStore = useUserStore()
	const instance = getCurrentInstance()
	
	const closePub = () => {
		userStore.setPubShowState({key:'indexShow',value:false})
	}
	const wxPubRef = ref()
	const openWxPop = () => {
		wxPubRef.value.showPop(true)
	}
	const tabs = ref([{value: 1,text: '订阅'},{value: 3,text: '最新'},{value: 2,text: '全部'}])
	const tabs2 = [{
			value: 1,
			text: '销量',
		},
		{
			value: 2,
			text: '最新',
		}
	]
	
	const list = ref([])

	const currentTab = ref(1)
	const currentTab2 = ref(1)
	
	const showSharePopup = ref(false)
	const shareId = ref('')
	
	if(userStore.userInfo && userStore.userInfo.agentLevel === 1){
		currentTab.value = 4
	}
	
	const setTbas = () => {
		if(userStore.userInfo && userStore.userInfo.agentLevel !== 0){
			tabs.value = [{value: 1,text: '订阅'},{value: 4,text: '推广'},{value: 3,text: '最新'},{value: 2,text: '全部'}]
		}
	}

	const onClickTab = (index) => {
		if (userStore.isLogin) {
			currentTab.value = index
			refresh()
		} else {
			uni.navigateTo({
				url: '/pagesA/login/login'
			})
		}
	}
	const onClickTab2 = (index) => {
		if (userStore.isLogin) {
			currentTab2.value = index
			refresh()
		} else {
			uni.navigateTo({
				url: '/pagesA/login/login'
			})
		}
	}

	const toMySubscribe = () => {
		uni.navigateTo({
				url: '/pagesH/my-subscribe/my-subscribe'
		})
	}
	
	const shareItem = ref({});
	const toShare = (item) => {
		if (userStore.isLogin) {
			shareId.value = item.id;
			shareItem.value = item;
			showSharePopup.value = true
		} else {
			uni.navigateTo({
				url: `/pagesA/login/login?from=${encodeURIComponent(`pages/home/home`)}`,
				events: {
					onLoginSuccess() {
						refresh()
					}
				}
			})
		}
	}

	const navBar = ref(null)
	const navBarHeight = computed(() => {
		const statusBarHeight = uni.getWindowInfo().statusBarHeight
		const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
		return navigationBarHeight
	})
	const safeAreaBottom = computed(() => {
		return uni.getSystemInfoSync().safeAreaInsets && uni.getSystemInfoSync().safeAreaInsets.bottom || 0
	})
	const menuButtonInfo = uni.getMenuButtonBoundingClientRect()

	const city = ref('')
	const defaultCity = '厦门市' // 默认定位城市
	const getLocation = () => {
		uni.authorize({
			scope: 'scope.userLocation',
			success: () => {
				uni.getLocation({
					success: ({ latitude, longitude }) => {
						// 定位获取不到城市，使用默认城市
						// if (latitude || longitude) {
							getPositionApi({ latitude, longitude }).then((res) => {
								city.value = res.city || defaultCity
								// userStore.setcityName(city.value)
								refresh()
							})
						// }
					},
					fail: (err) => {
						console.error('定位失败', err)
						refresh()
					}
				})
			},
			fail: () => {
				// 获取定位，用户拒绝后，使用默认城市
				city.value = defaultCity
				// userStore.setcityName(city.value)
				refresh()
			}
		})
	}
	
	const toSelectCity = () => {
		uni.navigateTo({
			url: '/pagesC/selectCity/selectCity',
			events: {
				onCitySelect: (data) => {
					console.log('城市', data)
					city.value = data
					instance.appContext.config.globalProperties.$city = data
					refresh()
				}
			}
		})
	}

	const gotoSearch = () => {
		uni.navigateTo({
			url: '/pagesC/search/search'
		})
	}

	const paging = ref(null)
	const queryParams = ref({
		type: currentTab.value,
		sortType: currentTab2.value,
		cityName: city.value,
		pageNum: 1,
		pageSize: 20,
	})
	const queryList = (pageNo, pageSize) => {
		queryParams.value.pageNum = pageNo
		queryParams.value.type = currentTab.value
		queryParams.value.sortType = currentTab2.value
		queryParams.value.cityName = city.value
		// console.log(city.value,'ddd')
		pageIndexActiveApi(unref(queryParams)).then(res => {
			paging.value.complete(res.list)
			console.log('查询城市：', city.value, '缓存城市', instance.appContext.config.globalProperties.$city)
			if (res.list && res.list.length && city.value) {
				// 有活动的城市不需要切换
				instance.appContext.config.globalProperties.$city = city.value
				// userStore.setcityName(city.value)
			}
			if (res.list && res.list.length === 0 && city.value && !instance.appContext.config.globalProperties.$city && !defaultCity.includes(city.value)) {
				uni.showModal({
					title: '当前城市还没有活动哦',
					showCancel: false,
					success() {
						city.value = defaultCity
						instance.appContext.config.globalProperties.$city = defaultCity
						// userStore.setcityName(city.value)
						refresh()
					}
				})
			}
		})
	}
	
	const refresh = () => {
		paging.value && paging.value.reload()
	}
	
	const refreshState = (data) => {
		if (currentTab.value === 1) {
			refresh()
		} else {
			list.value.forEach(it => {
				if (data.type === 'subscribe' && it.businessId === data.businessId) {
					if (data.state === 1) {
						it.subscribeState = 2
					} else {
						it.subscribeState = 1
					}
				}
			})
		}
	}
	
	const showBackToTop = ref(false)
	const handleScroll = ({ detail }) => {
		showBackToTop.value = detail.scrollTop > paging.value.windowHeight
	}
	const backToTop = () => {
		if (paging.value) {
			paging.value.scrollToTop()
		}
	}
	onMounted(() => {
		if(!instance.appContext.config.globalProperties.$city){//无值定位城市
			getLocation()
		}else{//全部缓存城市有值，复值，并且调取接口
			city.value = instance.appContext.config.globalProperties.$city
			refresh()
		}
		
		const token = uni.getStorageSync('token')
		if (token) {
			userStore.getWxRead()
			setTbas()
		}
	})
</script>
<style scoped lang="scss">
	.wx-pub{
		// position: relative;
		// z-index: 1;
		margin: 20rpx 32rpx;
		border-radius: 16rpx;
		background-color: rgba(255, 240, 234, 1);
		height: 72rpx;
		padding: 0 20rpx 0 28rpx;
		.wx-pub-text{
			font-family: PingFang SC;
			font-size: 28rpx;
			font-weight: 400;
			line-height: 40rpx;
			color: rgba(250, 69, 67, 1);
		}
		.wx-button{
			background-color: rgba(250, 69, 67, 1);
			border-radius: 32rpx;
			padding: 4rpx 24rpx;
			font-family: PingFang SC;
			font-size: 24rpx;
			font-weight: 400;
			line-height: 40rpx;
			text-align: center;
			color: #ffffff;
			margin-right: 12rpx;
		}
		.icon-clean{
			width: 40rpx;
		}
	}
</style>